<?php
require_once("controller/FEmail.class.php");
require_once("model/FUserBean.class.php");
require_once("admin/includes/util.php");
class FRegister {
	var $db;
 	var $smarty;	
	public function __construct($db, $smarty,$page='',$cat='',$product='') {
		$this->db = $db;
		$this->smarty = $smarty;
		$this->page = $page;
		$this->cat = $cat;
		$this->product = $product;
	}
	
	public function main() {
		if(isset($_POST['act']) && $_POST['act']=='newuser')
			$this->newCustomer();
		else if(isset($_POST['act']) && $_POST['act']=='login')	
			$this->login();
			
		else{	
			if($this->page == 'login' && !isset($_SESSION['cust_id'])){
				$this->smarty->display("login.tpl");	
			}else if($this->page == 'forgotPassword' && !isset($_SESSION['cust_id'])){	
				$this->smarty->display("forgotpassword.tpl");	
			}else if($this->page == 'registration' && !isset($_SESSION['cust_id'])){
				$countryBean = new FCountryBean($db, $smarty);
				$allcountry = $countryBean->get_all_country($this->db);	
				$this->smarty->assign('ALLCOUNTRY',$allcountry);
				$this->smarty->display("register.tpl");	
			}
		}
	}
	
	
	
	public function login() {
		$log = null;
		$pwd = null;
		unset($_SESSION['cust_id']);
		unset($_SESSION['cust_login']);
		unset($_SESSION['cust_name']);
		unset($_SESSION['err']);
		unset($_SESSION['file']);
		
		if($_POST['email'] != "" && $_POST['password'] != "") {
			$custommer = FUserBean::getCustomerByEmail($this->db, $_POST['email']);
			if($custommer != null) {
				$passCrypted = $custommer->password;
				if(crypt($_POST['password'], $passCrypted) == $passCrypted) {
					//echo crypt($_POST['password'], $passCrypted)."/";
					//echo $passCrypted;
					$_SESSION['cust_id'] 		= $custommer->user_id;
					$_SESSION['cust_login'] 	= $custommer->email;
					$_SESSION['cust_name'] 	= $custommer->firstname." ".$custommer->lastname;
					//include this file to set locale ID to SESSION variable
					//include_once("../localization.php");
					setcookie("fgold[cust_id]", $_SESSION['cust_id'], time()+3600);
					setcookie("fgold[cust_login]",$_SESSION['cust_login'], time()+3600);
					setcookie("fgold[cust_name]",$_SESSION['cust_name'], time()+3600);
				} else {
					$_SESSION['err'] = _("Invalid email address or password.");
				}
			} else {
				$_SESSION['err'] = _("Invalid email address or password.");
			}
		} else {
			if($_POST['email_address'] == "" && $_POST['password'] != "") {
				$_SESSION['err'] = _("Please type the email address.");
			} else if($_POST['email_address'] != "" && $_POST['password'] == "") {
				$_SESSION['err'] = _("Please type the password.");
			} else {
				$_SESSION['err'] = _("Please type the email address and password.");
			}
		}
		
		//Redirect to desire page
		if(!isset($_SESSION['err'])) {
			if($_POST['redirect_to'] == "") {
				ob_clean();
				header("Location: ./user/edit");
			} else {
				ob_clean();
				header("Location: ./user/edit");
			}
		} else {
			header("Location: ./login");
		}	
		
	}
	
	public function checkerror() {
		$ret = $this->validateCustomer();
		$type = array('ID' => -1, 'message' => $ret);
		echo array2json($type);	
	}
	
	public function newCustomer() {
			$type = array();
			$gender				= "";
			$gender					= "";
			$gender				= "";


			if(isset($_POST['firstname']))
				$firstname = $_POST['firstname'];
			if(isset($_POST['lastname']))
				$lastname = $_POST['lastname'];
			
			if(isset($_POST['email']))
				$email = $_POST['email'];
			if(isset($_POST['password']))
				$password = $_POST['password'];
			if(isset($_POST['country_id']))
				$country_id = $_POST['country_id'];
			if(isset($_POST['firstname']))
				$firstname = $_POST['firstname'];
			if(isset($_POST['lastname']))
				$lastname = $_POST['lastname'];	
			if(isset($_POST['city']))
				$city = $_POST['city'];
			if(isset($_POST['state']))
				$state = $_POST['state'];
			if(isset($_POST['country']))
				$country = $_POST['country'];	
			if(isset($_POST['contacts']))
				$contacts = @$_POST['contacts'];
															
		
			
			$cust = array('firstname' => $firstname,
						  'lastname' => $lastname,
						  'email' => $email,
						  'password' => $password,
						  'city' => $city,
						  'state' => $state,
					 	  'country' => $country,
					  	  'contacts' => $contacts);
			$ret = "";		
			$ret = $this->validateCustomer();
			if($ret['dem'] == 0) {					
				$id = FUserBean::saveCustomer($this->db, $cust);
				if($id > 0) {
					$type = array('ID' => 0);
					$host = $_SERVER['HTTP_HOST'].FOLDER_HOST;
					$code = crypt($to, '$ntp$');
					$from = FROMMAIL;
					$fromname = "F-Gold";
					$subject = "F-Gold Account Confirmation";
					$message = 	"Hello " . $firstname . " " . $lastname . "<br /><br />" .
								"Congratulations!You've just created an account on f-Gold.<br />" . 
							   	"Please confirm your -Gold account by clicking here:<br /><br /><br />" .
							   	"<a href='http://".$host."user/active/?code=" . $code . "&amp;id=" . $id . "'>http://$hostuser/active/?code=" . $code . "&amp;id=" . $id . "</a><br /><br /><br />" .
							   	"If you're unable to click on the link above, copy and paste it into your browser's address bar.<br /><br /><br />" .
								"Sincerely,<br /><br />";
					$header = "Content-type: text/html\r\nFrom: $from\r\nReply-to: $from";
					//FEmail::send_mail($email, $message, $subject, $from, $fromname, false);
					$type = array('ID' => 0, 'message' => 'Succecfull','dem'=>$ret['dem']);
					echo array2json($type);	
				}else{	
					$type = array('ID' => -1, 'message' => $ret);
					echo array2json($type);		
				}			
			} else {
				$type = array('ID' => -1, 'message' => 'Please enter (*)');
				echo array2json($type);	
			}
	}
	
	public function updateCustomer() {
			$type = array();
			$gender				= "";
			$firstname 			= "";
			$lastname 				= "";
			$dob 					= "";
			$email_address 		= "";
			$telephone			 	= "";
			$cellphone			 	= "";
			$fax				 	= "";
			$password			 	= FUserBean::getCustomerPassword($this->db, $_SESSION['cust_id']);
			$newsletter		 	= "";
			$street_address		 	= "";
			$postcode				 	= "";
			$city					 	= "";
			$state				 	= "";
			$country_id		 		= "";
			$company				 	= "";

			if(isset($_POST['gender']))
				$gender = $_POST['gender'];
			if(isset($_POST['firstname']))
				$firstname = $_POST['firstname'];
			if(isset($_POST['lastname']))
				$lastname = $_POST['lastname'];
			if(isset($_POST['dob']))
				$dob = date('Y-m-d',strtotime($_POST['dob']));
			if(isset($_POST['email']))
				$email = $_POST['email'];
			if(isset($_POST['telephone']))
				$telephone = $_POST['telephone'];
			if(isset($_POST['cellphone']))
				$cellphone = $_POST['cellphone'];		
			if(isset($_POST['fax']))
				$fax = $_POST['fax'];			
			if(isset($_POST['password']) && $_POST['password'] != "" && crypt($_POST['password'], '$ntp$') != $password)
				$password = crypt($_POST['password'], '$ntp$');
			if(isset($_POST['newsletter']))
				$newsletter = $_POST['newsletter'];
				
			if(isset($_POST['gender']))
				$gender = $_POST['gender'];	
			if(isset($_POST['firstname']))
				$firstname = $_POST['firstname'];
			if(isset($_POST['lastname']))
				$lastname = $_POST['lastname'];	
			if(isset($_POST['street_address']))
				$street_address = $_POST['street_address'];
			if(isset($_POST['postcode']))
				$postcode = $_POST['postcode'];
			if(isset($_POST['city']))
				$city = $_POST['city'];
			if(isset($_POST['state']))
				$state = $_POST['state'];
			if(isset($_POST['country_id']))
				$country_id = $_POST['country_id'];
				
			if(isset($_POST['gender']))
				$gender = $_POST['gender'];	
			if(isset($_POST['firstname']))
				$firstname = $_POST['firstname'];
			if(isset($_POST['lastname']))
				$lastname = $_POST['lastname'];	
			if(isset($_POST['street_address']))
				$street_address = $_POST['street_address'];
			if(isset($_POST['postcode']))
				$postcode = $_POST['postcode'];
			if(isset($_POST['city']))
				$city = $_POST['city'];
			if(isset($_POST['state']))
				$state = $_POST['state'];
			if(isset($_POST['country_id']))
				$country_id = $_POST['country_id'];	
			if(isset($_POST['company']))
				$company = $_POST['company'];
				
															
			
			$cust = array('gender' => $gender,
					  	  'firstname' => $firstname,
						  'lastname' => $lastname,
						  'dob' => $dob,
						  'email' => $email,
						  'telephone' => $telephone,
						  'cellphone' => $cellphone,
						  'fax' => $fax,
						  'password' => $password,
						  'newsletter' => $newsletter,
						  'gender' => $gender,
						  'firstname' => $firstname,
						  'lastname' => $lastname,
						  'street_address' => $street_address,
						  'postcode' => $postcode,
						  'city' => $city,
						  'state' => $state,
					 	  'country_id' => $country_id,
						  'gender' => $gender,
					 	  'firstname' => $firstname,
						  'lastname' => $lastname,
						  'street_address' => $street_address,
						  'postcode' => $postcode,
						  'city' => $city,
						  'state' => $state,
					 	  'country_id' => $country_id,
					  	  'company' => $company,
					  	  'id' => $_SESSION['cust_id']);
			$ret = "";		
			$ret = $this->validateCustomer();
			if($ret['dem'] == 0) {					
				FUserBean::updateCustomer($this->db, $cust);
			} else {
				$type = array('ID' => -1, 'message' => $ret);
				echo array2json($type);
			}
			
	}
	
	
	
	public function forgotPassword() {
		$msg = "";
		if(isset($_POST['email']) && $_POST['email'] != ""){
			$msg = "";
			$email = $_POST['email'];
			$check = $this->check_email_address($email);
			if($check == false){
				$msg .= "Invalid email address.";
			}else{
				$exists = FUserBean::ExistsByEmail($this->db,$email);
				if($exists == "")
				{
					$msg .= "This email address not exists.";
				}
			}
		}else{
			$msg .= "Invalid email address.";
		}
		if($msg == ""){
			$time = time();
			$get_code = md5($time); // tao 6 so ngau nhien
			$pass= substr($get_code, 0, 10);
			$passcrypt = crypt($pass, '$ntp$');
			FUserBean::updatePassword($this->db, $email, $passcrypt);
			
			$type = array('ID' => 0);
			$host = $_SERVER['HTTP_HOST'].FOLDER_HOST;
			$code = crypt($to, '$ntp$');
			$from = FROMMAIL;
			$fromname = "T & L Tec GdbR";
			$subject = "Your new password for GunWebshop";
			$message = 	"Hello,<br /><br />" .
						"Your Login: $email<br />" .
						"Your Password: $pass<br /><br /><br />" .
						"Sincerely,<br /><br />" . 
						"T & L Tec GdbR<br />" .
						"Plattlinger Strasse 5a<br />" .
						"93055 Regensburg<br />" .
						"Email: info@guncms.de<br />" .
						"Germany";
			$header = "Content-type: text/html\r\nFrom: $from\r\nReply-to: $from";
			FgcmsEmail::send_mail($_POST['email'], $message, $subject, $from, $fromname, false);
			header("Location: ./?page=send_access");
		}else{
			setcookie("message", $msg,time()+10);
			header("Location: ./?page=forgot_password");
		}	
	}
	
	/**
	 * @brief check validation of Customer information
	 * @retval error_message
	 * @date 2008/08/07
	**/
	public function checkValidDate($mydate) 
	{
    	list($yy,$mm,$dd)=explode("-",$mydate);
    	if (is_numeric($yy) && is_numeric($mm) && is_numeric($dd))
    	{
       	 return checkdate($mm,$dd,$yy);
    	}
    	return false;           
	}
	
	public function check_email_address($email) {
    	// First, we check that there's one @ symbol, and that the lengths are right
    	if (!ereg("^[^@]{1,64}@[^@]{1,255}$", $email)) {
    	// Email invalid because wrong number of characters in one section, or wrong number of @ symbols.
    	return false;
    	}
    	// Split it into sections to make life easier
    	$email_array = explode("@", $email);
    	$local_array = explode(".", $email_array[0]);
   		for ($i = 0; $i < sizeof($local_array); $i++) {
   			if (!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$", $local_array[$i])) {
   			return false;
   			}
   		}
   		if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1]))  // Check if domain is IP. If not, it should be valid domain name
   		{
   			$domain_array = explode(".", $email_array[1]);
   			if (sizeof($domain_array) < 2) 
   			{
   			return false; // Not enough parts to domain
   			}
   			for ($i = 0; $i < sizeof($domain_array); $i++) 
   			{
   				if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$", $domain_array[$i])) 
   				{
   				return false;
   				}
   			}
   		}
   		return true;
	}
	
	public function validateCustomer()
    {
    	$msg = array();
		$msg["gender"] = '';
		/*$msg["firstname"] = '';
		$msg["lastname"] = '';*/
		//$msg["dob"] = '';
		$msg["gender"] = '';
		$msg["firstname"] = '';
		$msg["lastname"] = '';
		$msg["street_address"] = '';
		$msg["postcode"] = '';
		$msg["city"] = '';
		$msg["state"] = '';
		$msg["country_id"] = '';
		$msg["gender"] = '';
		$msg["firstname"] = '';
		$msg["lastname"] = '';
		$msg["street_address"] = '';
		$msg["postcode"] = '';
		$msg["city"] = '';
		$msg["state"] = '';
		$msg["country_id"] = '';
		$msg["telephone"] = '';
		$msg["fax"] = '';
		$msg["email"] = '';
		$msg["password"] = '';
		$msg["confirmpassword"] = '';
		$dem =0;
		
		if(isset($_POST['first_name']) && $_POST['first_name'] == ""){
			$msg["first_name"] = "Your first name could not be empty.";
			$dem++;
		}
		if(isset($_POST['lastname']) && $_POST['lastname'] == ""){
			$msg["lastname"]= "Your last name could not be empty.";
			$dem++;
		}
		
		if(isset($_POST['city']) && $_POST['city'] == ""){
			$msg["city"]= "Your city could not be empty.";
			$dem++;
		}
		
		if(isset($_POST['country']) && $_POST['country'] == ""){
			$msg["country"]= "Please select your country.";
			$dem++;
		}
		
		
		if(isset($_POST['email']) && $_POST['email'] == ""){
			$msg["email"]= "Your email address could not be empty.";
			$dem++;
		}
		if(isset($_POST['email']) && $_POST['email'] != ""){
			$flag = $this->check_email_address($_POST['email']);
			if($flag == false){
				$msg["email"]= "Invalid email address.";
				$dem++;
			}else{
				if(isset($_SESSION['cust_id'])){
					$email = FUserBean::getCustomerEmail($this->db, $_SESSION['cust_id']);
					if($_POST['email'] != $email)
					{
						$email = FUserBean::getAllEmail($this->db);
						if($email!=""){
							foreach ($email as $item){
								if($item->email == $_POST['email']){	
									$msg["email"]= "This email address already exists.";
									$dem++;
								} 
							}
						}
					}
				}else{
						$email = FUserBean::getCustomerByEmail($this->db,$_POST['email']);
						if($email!=""){
							$msg["email"]= "This email address already exists.";
							$dem++;
						}
				}
			}
			
		}
		if($_POST['email_confirm'] != "" && $_POST['email_confirm'] != $_POST['email']){
					$msg["email_confirm"]= "Your email confirmation must match your email.";	
					$dem++;
				}
		if($_POST['captcha'] == "")
		{
			$msg["captcha"]= "Please enter code .";
			$dem++;
		}
		else if($_POST['captcha'] != $_SESSION["captcha_str"])
		{
				$msg["captcha"]= "Wrong code. Please enter again!";
				$dem++;
		}

		if(isset($_SESSION['cust_id']))
		{
			if(isset($_POST['password']) && $_POST['password'] != "")
			{
				if(strlen($_POST['password']) <5){
					$msg["password"]= "Your password must contain at least 5 characters.";
					$dem++;
				}
				$password = FUserBean::getCustomerPassword($this->db, $_SESSION['cust_id']);
				if(crypt($_POST['password'], '$ntp$') != $password){
					if($_POST['confirmpassword'] == ""){
						$msg["password"]= "Your password confirmation could not be empty.";
						$dem++;
					}
					if($_POST['confirmpassword'] != "" && $_POST['confirmpassword'] != $_POST['password']){
						$msg["confirmpassword"]= "Your password confirmation must match your password.";	
						$dem++;
					}
				}
			}
		}else{
			if(isset($_POST['password']) && $_POST['password'] != "")
			{
				if(strlen($_POST['password']) <5){
					$msg["password"]= "Your password must contain at least 5 characters.";
					$dem++;
				}
				if($_POST['password_confirm'] == ""){
					$msg["password"]= "Your password confirmation could not be empty.";
					$dem++;
				}
				if($_POST['password_confirm'] != "" && $_POST['password_confirm'] != $_POST['password']){
					$msg["password_confirm"]= "Your password confirmation must match your password.";	
					$dem++;
				}
			}
		}
		
		$msg["dem"] = $dem;
		return $msg;
    }
	
}
?>
